import React, {Component} from 'react'
import { withRouter } from 'react-router-dom'
import { Modal } from 'antd'

import LinkButton from '../../components/LinkButton'
import {reqWeather} from '../../api'
import menuList from '../../config/menu_config'
import {formatDate} from '../../utils/date_utils'
import memoryUtils from '../../utils/memory_utils'
import storageUtils from '../../utils/storage_utils'
import './Header.less'

const { confirm } = Modal

class Header extends Component {
  state = {
    currentTime: formatDate(Date.now()),
    dayPictureUrl: '', // 天气的图片
    weather: '' //天气的文本
  }

  getTime = () => {
    // 每隔 1s 获取当前时间, 并更新状态数据 currentTime
    this.timer = setInterval(() => {
      const currentTime = formatDate(Date.now())
      this.setState({currentTime})
    }, 1000)
  }

  getWeather = async () => {
    const { dayPictureUrl, weather } = await reqWeather('河南')
    this.setState({ dayPictureUrl, weather })
  }

  // 获取当前 title
  getTile = () => {
    // 获取当前请求路径
    const { pathname } = this.props.location
    let title
    menuList.forEach(item => {
      // 如果当前 item对象的key与pathname一样, item的title就是要显示的title
      if (item.key === pathname) {
        title = item.title
      } else if (item.children) {
        // 在所有子 item中查找匹配
        const cItem = item.children.find(cItem => pathname.includes(cItem.key))
        // 如果有值, 说明有匹配的
        if (cItem) {
          title = cItem.title
        }
      }
    })
    return title
  }

  // 退出登录
  logout = () => {
    confirm({
      title: '请问您要退出吗?',
      okText: '确定',
      okType: 'danger',
      cancelText: '取消',
      onOk: () => {
        // console.log('OK');
        // 删除保存的 user 数据
        storageUtils.removeUser()
        memoryUtils.user = {}
        // 跳转到 login
        this.props.history.replace('/login')
      },
      onCancel() {
      },
    })
  }

  UNSAFE_componentWillMount () {
    // 组件销毁之前清除 定时器
    clearInterval(this.timer)
    this.timer = null
  }

  componentDidMount() {
    // 获取当前时间
    this.getTime()
    // 获取当前天气
    this.getWeather()
  }


  render() {
    const {currentTime, dayPictureUrl, weather} = this.state
    const {username} = memoryUtils.user
    // 得到当前需要显示的 title
    const title = this.getTile()

    return (
      <header className='header'>
        <div className='header-top'>
          <span>欢迎, {username}</span>
          <LinkButton onClick={this.logout}>退出</LinkButton>
        </div>
        <div className='header-bottom'>
          <div className='header-bottom-left'>{title}</div>
          <div className='header-bottom-right'>
            <span>{currentTime}</span>
            <img src={dayPictureUrl} alt=""/>
            <span>{weather}</span>
          </div>
        </div>
      </header>
    )
  }
}

export default withRouter(Header)
